package info.emamian.droplet.core.controllers;

import info.emamian.droplet.core.domain.BasicSMS;
import info.emamian.droplet.core.provider.DHTwilio;
import info.emamian.droplet.core.services.SMSService;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/sms")
public class ProviderSMSController {
	private static final Logger log = LoggerFactory.getLogger(ProviderSMSController.class);
	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private SMSService smsService;

	@RequestMapping("/twilio")
	public void getSMS(HttpServletRequest request, HttpServletResponse response) throws IOException {
		log.info("new sms arrived at {} from DHTwilio", new Date());
		BasicSMS incoming = DHTwilio.convertToBasicSMS(request);
		if (incoming == null) {
			log.error("Error handling incoming sms by Twilio");
			// TODO handle error response
		} else {
			mongoTemplate.save(incoming);
		}
		String responseText = smsService.getAnswerFromAppropriateHandler(incoming);
		if (responseText == null || responseText.isEmpty())
			responseText = "Hello " + incoming.getFrom() + ", we received you message of '" + incoming.getBody()
					+ "'.  Please visit us at http://beta.droplet-health.com or send 'help' or 'cmd' for the list of commands available.";
		BasicSMS resp = DHTwilio.writeTwimlResponse(incoming, response, responseText);
		if (resp == null) {
			// could not save response
			log.error("Error sending response SMS to incoming sms:{}", incoming);
			// TODO handle error response
		} else {
			mongoTemplate.save(resp);
		}
	}

	@RequestMapping(value = "/twilio/test", method = RequestMethod.GET)
	public String testSMSGenerator(Model model) {
		return "sms/test";
	}

	@RequestMapping(value = "/twilio/test", method = RequestMethod.POST)
	@ResponseBody
	public String testSMSGenerator(HttpServletRequest request) {
		BasicSMS incoming = DHTwilio.convertToBasicSMS(request);
		String responseText = smsService.getAnswerFromAppropriateHandler(incoming);
		return responseText;
	}

}
